import os

import yaml

from common.recordlog import logs
from conf.setting import DIR_BASE
from conf.setting import FILE_PATH

class ReadYamlData:
    def __init__(self):
        pass

    # 获取testcase_yaml文件中的baseinfo、testcase,以列表格式传递给测试用例
    def get_testcase_yaml(self,file):
        testcase_list = []
        try:
            with open(file,"r",encoding="utf-8") as f:
                data = yaml.safe_load(f)
                for a in data:
                    baseInfo = a.get("baseInfo")
                    # 获取到的testcase为列表，需要取第一个字典元素
                    testCase = a.get("testCase")[0]
                    param = [baseInfo, testCase]
                    testcase_list.append(param)
            return testcase_list
        except UnicodeDecodeError:
            logs.error(
                f"[{file}]文件编码格式错误，--尝试使用utf-8编码解码YAML文件时发生了错误，请确保你的yaml文件是UTF-8格式！")
        except FileNotFoundError:
            logs.error(f'[{file}]文件未找到，请检查路径是否正确')
        except Exception as e:
            logs.error(f'获取【{file}】文件数据时出现未知错误: {str(e)}')

    # 获取extract_yaml文件中的某个节点的值
    def get_extract_yaml(self, node_name, second_node_name=None):

        # 若extract_yaml文件不存在，则创建
        if not os.path.exists(FILE_PATH["EXTRACT"]):
            logs.error("extract.yaml文件不存在")
            file = open(FILE_PATH["EXTRACT"], "w", encoding="utf-8")
            file.close()
            logs.info("extract.yaml文件创建成功")

        try:
            # 获取extract_yaml文件中对应的节点值或子节点值
            with open(FILE_PATH["EXTRACT"], "r", encoding="utf-8") as f:
                ext_data = yaml.safe_load(f)
                if second_node_name is None:
                    return ext_data[node_name]
                else:
                    return ext_data[node_name][second_node_name]
        except Exception as e:
            logs.error(f"未找到extract_yaml文件中的节点值{node_name} {second_node_name},异常信息：{e}")

    # 往extract_yaml文件中写入数据
    def write_extract_yaml(self, value):
        file_path = FILE_PATH["EXTRACT"]
        if not os.path.exists(file_path):
            logs.error("extract.yaml文件不存在")
            file = open(FILE_PATH["EXTRACT"], "w", encoding="utf-8")
            file.close()
            logs.info("extract.yaml文件创建成功")

        try:
            with open(file_path, "a", encoding="utf-8") as f:
                # 判断入参value是否为字典，只有字典才能写入yaml文件
                if isinstance(value, dict):
                    # 将 Python 字典对象序列化为 YAML 格式的字符串
                    write_data = yaml.dump(value)
                    # 将数据写入文件
                    f.write(write_data)
                    logs.info("成功将数据写入extract_yaml文件")
                else:
                    logs.error("写入extract_yaml文件的数据必须为dict格式")
        except Exception as e:
            logs.error(f"写入extract_yaml文件失败，异常：{e}")

    def clean_extract_yaml_data(self):
        with open(FILE_PATH["EXTRACT"], "w", encoding="utf-8") as f:
            # 清空文件内容 的操作，它会将文件大小截断为 0 字节
            f.truncate(0)
            logs.info("extract_yaml文件内容已清空")



if __name__ == '__main__':
    data = ReadYamlData().get_testcase_yaml(os.path.join(DIR_BASE, "testcase", "login_csdn", "login_csdn.yml"))
    print(data)
